package top.archiesean.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import top.archiesean.io.Resources;
import top.archiesean.pojo.Configuration;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author ArchieSean
 * @create 2023/7/11
 */
public class XMLConfigBuilder {

    private final Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 该方法就是将配置文件进行解析，封装成configuration对象
     *
     * @param inputStream 字节输入流
     * @return obj
     */
    public Configuration parseConfig(InputStream inputStream) {
        try {
            Document document = new SAXReader().read(inputStream);
            //获取根标签
            Element rootElement = document.getRootElement();

            List<Element> list = rootElement.selectNodes("//property");
            //用于封装xml中配置信息
            Properties properties = new Properties();
            list.forEach(ele -> {
                String name = ele.attributeValue("name");
                String value = ele.attributeValue("value");
                properties.setProperty(name, value);
            });

            //创建连接池
            ComboPooledDataSource dataSource = new ComboPooledDataSource();
            //连接驱动
            dataSource.setDriverClass(properties.getProperty("driverClass"));
            //url
            dataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
            //用户名
            dataSource.setUser(properties.getProperty("username"));
            //密码
            dataSource.setPassword(properties.getProperty("password"));
            configuration.setDataSource(dataSource);

            //mapper.xml解析： 拿到路径---字节输入流---dom4j进行解析
            List<Element> mapperList = rootElement.selectNodes("//mapper");
            mapperList.forEach(mapper -> {
                String mapperPath = mapper.attributeValue("resource");
                InputStream stream = Resources.getResourceAsStream(mapperPath);
                XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
                xmlMapperBuilder.parse(stream);
            });
        } catch (Exception e) {
            System.out.println("解析xml失败");
        }
        return configuration;
    }
}
